package com.tezign.intelligence.mini.dam.aifamilyconsultant.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.tezign.intelligence.mini.dam.aifamilyconsultant.bean.FamilyMemberBean;
import com.tezign.intelligence.mini.dam.aifamilyconsultant.bean.ResponseBean;
import com.tezign.intelligence.mini.dam.aifamilyconsultant.bean.UserStatusEnum;
import com.tezign.intelligence.mini.dam.aifamilyconsultant.bean.req.CreateAndAddRoleReq;
import com.tezign.intelligence.mini.dam.aifamilyconsultant.bean.resp.FamilyInfoVO;
import com.tezign.intelligence.mini.dam.aifamilyconsultant.constant.Constant;
import com.tezign.intelligence.mini.dam.aifamilyconsultant.entity.Family;
import com.tezign.intelligence.mini.dam.aifamilyconsultant.entity.FamilyMember;
import com.tezign.intelligence.mini.dam.aifamilyconsultant.entity.User;
import com.tezign.intelligence.mini.dam.aifamilyconsultant.interceptor.FamilyStore;
import com.tezign.intelligence.mini.dam.aifamilyconsultant.interceptor.UserStore;
import com.tezign.intelligence.mini.dam.aifamilyconsultant.service.IFamilyMemberService;
import com.tezign.intelligence.mini.dam.aifamilyconsultant.service.IFamilyService;
import com.tezign.intelligence.mini.dam.aifamilyconsultant.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


/**
 * <p>
 * 家庭信息 前端控制器
 * </p>
 *
 * @author six
 * @since 2024-11-16
 */
@Api(tags = "家庭管理")
@Slf4j
@CrossOrigin("*")
@RestController
@RequiredArgsConstructor
@RequestMapping(Constant.APPLICATION_NAME + "/family")
public class FamilyController {


	private final IFamilyService familyService;

	private final IFamilyMemberService familyMemberService;

	private final RedisTemplate<String, Object> redisTemplate;

	private final IUserService userService;

	// 创建家庭
	@GetMapping("/create")
	@ApiOperation(value = "获取家庭code")
	public ResponseBean<String> create(@RequestParam("familyName") String familyName) {
		log.info("创建家庭 familyName:{}", familyName);
		Family family = new Family();
		family.setName(familyName);
		// 随机生成家庭号 4位
		String code = familyService.generateNewCode();
		family.setCode(code);
		// 过期时间 30分钟
		redisTemplate.opsForValue().set(code, JSONUtil.toJsonStr(family), 30, TimeUnit.MINUTES);
		return new ResponseBean<String>().success(code);
	}

	// 首次创建家庭并添加角色
	@PostMapping("/createAndAddRole")
	@ApiOperation(value = "首次创建家庭并添加角色")
	@Transactional(rollbackFor = Exception.class)
	public ResponseBean<Long> createAndAddRole(@RequestBody CreateAndAddRoleReq req) {
		log.info("首次创建家庭并添加角色 req:{}", req);
		String code = req.getCode();
		Object object = redisTemplate.opsForValue().get(code);
		if (object == null) {
			return new ResponseBean<Long>().exception(UserStatusEnum.ERROR.addErrorMsg("家庭号不存在或者已过期"));
		}
		Family bean = JSONUtil.toBean(JSONUtil.toJsonStr(object), Family.class);
		familyService.save(bean);
		// 删除redis缓存
		redisTemplate.delete(code);
		Long userId = UserStore.getUserId();

		// 添加角色
		return getLongResponseBean(req, bean, userId);
	}

	// 通过家庭吗加入家庭
	@PostMapping("/joinFamily")
	@ApiOperation(value = "通过家庭吗加入家庭")
	public ResponseBean<Long> joinFamily(@RequestBody CreateAndAddRoleReq req) {
		log.info("通过家庭吗加入家庭 req:{}", req);
		String familyCode = req.getCode();
		Family family = familyService.lambdaQuery().eq(Family::getCode, familyCode).one();
		if (family == null) {
			return new ResponseBean<Long>().exception(UserStatusEnum.ERROR.addErrorMsg("家庭号不存在"));
		}
		Long userId = UserStore.getUserId();
		FamilyMember familyMember = familyMemberService.lambdaQuery().eq(FamilyMember::getFamilyId, family.getId()).eq(FamilyMember::getUserId, userId).one();
		if (familyMember != null) {
			return new ResponseBean<Long>().exception(UserStatusEnum.ERROR.addErrorMsg("您已加入该家庭"));
		}
		return getLongResponseBean(req, family, userId);

	}

	private ResponseBean<Long> getLongResponseBean(CreateAndAddRoleReq req, Family family, Long userId) {
		FamilyMember member = new FamilyMember();
		member.setFamilyId(family.getId());
		member.setUserId(userId);
		member.setRole(req.getRole());
		familyMemberService.save(member);
		userService.lambdaUpdate().set(User::getActiveFamilyId, member.getFamilyId()).eq(User::getId, userId).update();
		return new ResponseBean<Long>().success(family.getId());
	}


	// 获取家庭信息以及成员信息
	@GetMapping("/getFamilyInfo")
	@ApiOperation(value = "获取家庭信息以及成员信息")
	public ResponseBean<FamilyInfoVO> getFamilyInfo(@RequestParam("familyId") Long familyId) {
		log.info("获取家庭信息以及成员信息 familyId:{}", familyId);
		Family family = familyService.getById(familyId);
		if (family == null) {
			return new ResponseBean<FamilyInfoVO>().exception(UserStatusEnum.ERROR.addErrorMsg("家庭不存在"));
		}
		FamilyInfoVO familyInfoVO = BeanUtil.copyProperties(family, FamilyInfoVO.class);
		List<FamilyMember> members = familyMemberService.lambdaQuery().eq(FamilyMember::getFamilyId, familyId).list();
		List<FamilyMemberBean> memberBeans = members.stream().map(x -> BeanUtil.copyProperties(x, FamilyMemberBean.class)).collect(Collectors.toList());
		familyInfoVO.setFamilyMembers(memberBeans);
		return new ResponseBean<FamilyInfoVO>().success(familyInfoVO);
	}

	// 获取用户家庭列表
	@GetMapping("/getFamilyList")
	@ApiOperation(value = "获取用户家庭列表")
	public ResponseBean<List<FamilyInfoVO>> getFamilyList() {
		Long userId = UserStore.getUserId();
		List<FamilyMember> familyMembers = familyMemberService.lambdaQuery().eq(FamilyMember::getUserId, userId).list();

		List<Long> familyIds = familyMembers.stream().map(FamilyMember::getFamilyId).collect(Collectors.toList());
		List<Family> families = familyService.listByIds(familyIds);
		List<FamilyInfoVO> familyInfoVOS = families.stream().map(x -> {
			FamilyInfoVO familyInfoVO = new FamilyInfoVO();
			BeanUtils.copyProperties(x, familyInfoVO);
			List<FamilyMember> members = familyMemberService.lambdaQuery().eq(FamilyMember::getFamilyId, x.getId()).list();
			List<FamilyMemberBean> memberBeans = members.stream().map(y -> BeanUtil.copyProperties(y, FamilyMemberBean.class)).collect(Collectors.toList());
			familyInfoVO.setFamilyMembers(memberBeans);
			return familyInfoVO;
		}).collect(Collectors.toList());
		return new ResponseBean<List<FamilyInfoVO>>().success(familyInfoVOS);
	}

	// 切换用户家庭
	@GetMapping("/switchFamily")
	@ApiOperation(value = "切换用户家庭")
	public ResponseBean<Boolean> switchFamily(@RequestParam("familyId") Long familyId) {
		Long userId = UserStore.getUserId();
		FamilyMember familyMember = familyMemberService.lambdaQuery().eq(FamilyMember::getUserId, userId).eq(FamilyMember::getFamilyId, familyId).one();
		if (familyMember == null) {
			return new ResponseBean<Boolean>().exception(UserStatusEnum.ERROR.addErrorMsg("家庭不存在"));
		}
		userService.lambdaUpdate().set(User::getActiveFamilyId, familyId).eq(User::getId, userId).update();
		return new ResponseBean<Boolean>().success(true);
	}

	// 获取家庭用户角色
	@GetMapping("/getRole")
	@ApiOperation(value = "获取家庭用户角色")
	public ResponseBean<String> getRole() {
		Long familyId = FamilyStore.getFamilyId();
		Family family = familyService.getById(familyId);
		Long userId = UserStore.getUserId();
		if (family == null) {
			return new ResponseBean<String>().exception(UserStatusEnum.ERROR.addErrorMsg("家庭不存在"));
		}
		FamilyMember familyMember = familyMemberService.lambdaQuery().eq(FamilyMember::getUserId, userId).eq(FamilyMember::getFamilyId, familyId).one();
		if (familyMember == null) {
			return new ResponseBean<String>().exception(UserStatusEnum.ERROR.addErrorMsg("家庭不存在"));
		}
		return new ResponseBean<String>().success(familyMember.getRole());
	}

}
